<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="listQuery.username" placeholder="用户名" clearable style="width: 200px;" class="filter-item" />
      <el-select
        v-model="listQuery.status"
        placeholder="状态"
        clearable
        style="width: 100px;margin-left: 5px"
        class="filter-item"
      >
        <el-option v-for="item in statusOptions" :key="item.key" :label="item.value" :value="item.key" />
      </el-select>
      <el-button
        v-waves
        class="filter-item"
        type="primary"
        style="margin-left: 5px"
        icon="el-icon-search"
        @click="handleFilter"
      >
        搜索
      </el-button>
      <el-button class="filter-item" style="margin-left: 5px;" type="primary" icon="el-icon-edit" @click="handleCreate">
        添加
      </el-button>
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      max-height="600px"
    >
      <el-table-column label="ID" prop="id" align="center" />
      <el-table-column label="用户名" prop="username" align="center" />
      <el-table-column label="昵称" prop="nickname" align="center" />
      <el-table-column label="头像" align="center">
        <template slot-scope="{row}">
          <el-popover placement="top-start" title="" trigger="hover">
            <img :src="row.avatar" alt="" style="width: 150px;height: 150px">
            <img slot="reference" :src="row.avatar" style="width: 30px;height: 30px">
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column label="邮箱" prop="email" align="center" />
      <el-table-column label="状态" align="center">
        <template slot-scope="{row}">
          <el-tag :type="row.status === 0 ? 'danger' : 'success'">
            {{ row.status | statusFilter }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="登录ip" prop="loginIP" align="center" />
      <el-table-column label="登录时间" align="center">
        <template slot-scope="{row}">
          <span>{{ row.loginAt | parseTime('{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="230" class-name="small-padding fixed-width">
        <template slot-scope="{row}">
          <el-button-group>
            <el-button type="primary" size="mini" @click="handleEdit(row)">
              编辑
            </el-button>
            <el-button type="primary" size="mini" @click="handleAssign(row)">
              分配角色
            </el-button>
            <el-button type="primary" size="mini" @click="handleReset(row)">
              重置密码
            </el-button>
            <el-button size="mini" type="danger" @click="handleDelete(row)">
              删除
            </el-button>
          </el-button-group>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.limit"
      @pagination="getList"
    />

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="temp"
        label-position="left"
        label-width="70px"
        style="width: 400px; margin-left:50px;"
      >
        <el-form-item label="用户名" prop="username" required>
          <el-input v-model="temp.username" />
        </el-form-item>
        <el-form-item label="昵称" prop="nickname" required>
          <el-input v-model="temp.nickname" />
        </el-form-item>
        <el-form-item label="密码" prop="password" required>
          <el-input v-model="temp.password" />
        </el-form-item>
        <el-form-item label="头像" prop="avatar">
          <el-input v-model="temp.avatar" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="temp.email" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-switch v-model="temp.status" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          确认
        </el-button>
      </div>
    </el-dialog>

    <el-dialog title="分配角色" :visible.sync="dialogRolesVisible" :close-on-click-modal="false">
      <el-select v-model="roleTemp.roles" multiple placeholder="选择角色" style="width: 100%;">
        <el-option v-for="item in roseList" :key="item.id" :label="item.roleName" :value="item.id" />
      </el-select>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogRolesVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="assignRoles">
          确认
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import request from '@/utils/request'
import Pagination from '@/components/Pagination'
import waves from '@/directive/waves'

const statusOptions = [
  { key: 0, value: '禁用' },
  { key: 1, value: '启用' }
]

const calendarTypeKeyValue = statusOptions.reduce((acc, cur) => {
  acc[cur.key] = cur.value
  return acc
}, {})

export default {
  name: 'List',
  components: { Pagination },
  directives: { waves },
  filters: {
    statusFilter(type) {
      return calendarTypeKeyValue[type]
    }
  },
  data() {
    return {
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      statusOptions,
      listQuery: {
        page: 1,
        limit: 20,
        username: undefined,
        status: undefined
      },
      temp: {
        id: undefined,
        username: '',
        nickname: '',
        avatar: '',
        email: '',
        status: true
      },
      rules: {
        username: [{ required: true, message: '用户名必填', trigger: 'blur' }],
        nickname: [{ required: true, message: '昵称必填', trigger: 'blur' }],
        password: [{ required: true, message: '密码必填', trigger: 'blur' }]
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑管理员',
        create: '添加管理员'
      },
      dialogRolesVisible: false,
      roleTemp: {
        id: undefined,
        roles: []
      },
      roseList: []
    }
  },
  created() {
    this.getList()
    this.getRoleList()
  },
  methods: {
    getList() {
      this.listLoading = true
      request({
        url: '/admin/list',
        data: this.listQuery
      }).then(response => {
        this.list = response.data.items
        this.total = response.data.total

        this.listLoading = false
      })
    },
    handleFilter() {
      if (this.listQuery.username === '') {
        this.listQuery.username = undefined
      }
      if (this.listQuery.status === '') {
        this.listQuery.status = undefined
      }
      this.listQuery.page = 1
      this.getList()
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        username: '',
        nickname: '',
        avatar: '',
        email: '',
        status: true
      }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.temp.status = this.temp.status ? 1 : 0
          request({
            url: '/admin/add',
            data: this.temp
          }).then(() => {
            this.dialogFormVisible = false
            this.$message({
              message: '添加成功',
              type: 'success',
              duration: 2000
            })
            this.getList()
          })
        } else {
          this.$message({
            message: '请完善必填项',
            type: 'error',
            duration: 2000
          })
        }
      })
    },
    handleEdit(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.temp.status = this.temp.status === 1
      this.dialogStatus = 'edit'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.temp.status = this.temp.status ? 1 : 0
          console.log(this.temp)
          request({
            url: '/admin/edit',
            data: this.temp
          }).then(() => {
            this.dialogFormVisible = false
            this.$message({
              message: '编辑成功',
              type: 'success',
              duration: 2000
            })
            this.getList()
          })
        } else {
          this.$message({
            message: '请完善必填项',
            type: 'error',
            duration: 2000
          })
        }
      })
    },
    handleDelete(row) {
      const id = row.id
      this.$msgbox.confirm(
        '确认删除管理员？',
        'Warning',
        {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(() => {
        request({
          url: '/admin/delete',
          data: { id: id }
        }).then(() => {
          this.$message({
            message: '删除成功',
            type: 'success',
            duration: 2000
          })
          this.getList()
        })
      })
    },
    handleReset(row) {
      const id = row.id
      this.$msgbox.confirm(
        '确认重置密码？',
        'Warning',
        {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(() => {
        request({
          url: '/admin/resetPwd',
          data: { id: id }
        }).then(response => {
          this.$msgbox.alert(
            '重置后密码为：<h3>' + response.data.reset_password + '</h3>',
            '重置成功',
            {
              dangerouslyUseHTMLString: true
            })
        })
      })
    },
    handleAssign(row) {
      this.roleTemp.id = row.id
      this.dialogRolesVisible = true
      // 获取选中管理员所拥有的角色
      request({
        url: '/role/getRolesByAdminID',
        data: { id: row.id }
      }).then(response => {
        this.roleTemp.roles = response.data
      })
    },
    getRoleList() {
      request({
        url: '/role/selectList'
      }).then(response => {
        this.roseList = response.data
      })
    },
    assignRoles() {
      request({
        url: '/admin/assignRoles',
        data: this.roleTemp
      }).then(() => {
        this.$message({
          message: '分配成功',
          type: 'success',
          duration: 2000
        })
        this.dialogRolesVisible = false
      })
    }
  }
}
</script>

